<template>
  <div v-loading="tinymceLoading">
    <div :class="{ fullscreen: fullscreen }" class="tinymce-container" :style="{ width: containerWidth }">
      <div :id="tinymceId" class="tinymce-textarea" />
    </div>
  </div>
</template>

<script>
import load from './dynamicLoadScript'
// const tinymceCDN = 'https://cdn.jsdelivr.net/npm/tinymce-all-in-one@4.9.3/tinymce.min.js';
const tinymceCDN = '/tinymce/tinymce.min.js'

export default {
  name: 'Tinymce',
  components: { },
  props: {
    value: {
      type: String,
      default: ''
    },
    height: {
      type: [Number, String],
      required: false,
      default: 360
    },
    width: {
      type: [Number, String],
      required: false,
      default: 'auto'
    },
    autoresize: {
      type: Boolean,
      default: () => false
    },
    showCusBtn: {
      type: Boolean,
      default: () => false
    },
    disabled: {
      type: Boolean,
      default: () => false
    },
    isPreview: {
      type: Boolean,
      default: () => false
    },
    toolbarArr: {
      type: Array,
      default: () => ['searchreplace fontsizeselect bold italic underline strikethrough alignleft aligncenter alignright outdent indent  blockquote undo redo removeformat code codesample', 'bullist numlist link image charmap preview anchor pagebreak table emoticons forecolor backcolor fullscreen']
    }
  },
  data() {
    return {
      hasChange: false,
      hasInit: false,
      fullscreen: false,
      languageTypeList: {
        en: 'en',
        zh: 'zh_CN',
        es: 'es_MX',
        ja: 'ja'
      },
      menubar: 'file edit insert view format table',
      plugins: 'advlist anchor autolink autosave code codesample directionality emoticons fullscreen image insertdatetime link lists media nonbreaking pagebreak preview save searchreplace table template visualblocks visualchars wordcount',
      tinymceLoading: true,
      wordcount: 0
    }
  },
  computed: {
    containerWidth() {
      const width = this.width
      if (/^[\d]+(\.[\d]+)?$/.test(width)) {
        // matches `100`, `'100'`
        return `${width}px`
      }
      return width
    },
    tinymceId() {
      return 'vue-tinymce-' + +new Date() + ((Math.random() * 1000).toFixed(0) + '')
    }

  },
  watch: {
    value: {
      handler(val) {
        // console.log('tinymcetinymceval', val)
        if (!this.hasChange && this.hasInit) {
          this.$nextTick(() => window.tinymce.get(this.tinymceId).setContent(val || ''))
        }
      },
      immediate: true,
      deep: true
    }
  },
  mounted() {
    this.init()
  },
  activated() {
    if (window.tinymce) {
      this.initTinymce()
    }
  },
  deactivated() {
    this.destroyTinymce()
  },
  destroyed() {
    this.destroyTinymce()
  },
  methods: {
    init() {
      // dynamic load tinymce from cdn
      load(tinymceCDN, (err) => {
        if (err) {
          this.$message.error(err.message)
          return
        }
        setTimeout(() => {
          this.initTinymce()
        }, this.isPreview ? 0 : 1000)
      })
    },
    initTinymce() {
      const _this = this
      window.tinymce.init({
        selector: `#${this.tinymceId}`,
        language: this.languageTypeList['zh'],
        height: this.height,
        body_class: 'panel-body',
        object_resizing: true, // false时图片不能四边调整大小
        toolbar: this.toolbarArr,
        menubar: this.isPreview ? '' : this.menubar,
        inline: this.isPreview,
        plugins: this.plugins,
        end_container_on_empty_block: true,
        readonly: this.disabled,
        elementpath: true, // 隐藏底栏的元素路径
        branding: false, // 隐藏右下角技术支持
        powerpaste_word_import: 'propmt', // 参数可以是propmt, merge, clear
        powerpaste_html_import: 'propmt', // propmt, merge, clear
        powerpaste_allow_local_images: true,
        paste_data_images: true, // 允许粘贴图像
        paste_auto_cleanup_on_paste: false,
        paste_remove_styles: false,
        paste_remove_styles_if_webkit: false,
        // paste_strip_class_attributes:false,
        // paste_webkit_styles: true,
        valid_elements: '*[*]', // 这个能使paste_postprocess修改生效
        valid_children: '*[*]',
        // extended_valid_elements: 'style,link[href|rel],script',
        // custom_elements: 'style,link,~link,script',
        // extended_valid_elements: 'img[style|class|src|border|alt|title|hspace|vspace|width|height|align|name|loading]',
        code_dialog_height: 450,
        code_dialog_width: 1000,
        // advlist_bullet_styles: 'square',
        // advlist_number_styles: 'default',
        default_link_target: '_blank',
        link_title: false,
        fontsize_formats: '8pt 10pt 12pt 14pt 18pt 24pt 36pt',
        nonbreaking_force_tab: true, // inserting nonbreaking space &nbsp; need Nonbreaking Space Plugin
        content_style: 'img{max-width:100%;}',
        save_enablewhendirty: false, // 当内容无变化时禁用保存按钮
        init_instance_callback: editor => {
          if (_this.value) {
            editor.setContent(_this.value)
          }
          _this.hasInit = true
          editor.on('NodeChange Change KeyUp SetContent', () => {
            _this.hasChange = true
            _this.$nextTick(() => {
              _this.$emit('input', editor.getContent())
              _this.$emit('focus', editor)
              _this.wordcount = editor.plugins.wordcount.getCount()
            })
          })
        },
        setup(editor) {
          editor.on('FullscreenStateChanged', (e) => {
            _this.fullscreen = e.state
          })
        },
        convert_urls: false,
        paste_preprocess: function(plugin, args) { // 粘贴图片成功，返回的args.
          console.log('paste_preprocess', args)
        },
        paste_postprocess: function(editor, args) {
          console.log('paste_postprocess', args)
        },
        images_upload_handler: (blobInfo) => {
          // console.log(blobInfo, 'blobInfo')
          return new Promise((resolve) => {
            resolve('data:' + blobInfo.blob().type + ';base64,' + blobInfo.base64())
          })
        }
      })
      this.tinymceLoading = false
    },
    destroyTinymce() {
      const tinymce = window.tinymce.get(this.tinymceId)
      if (this.fullscreen) {
        tinymce.execCommand('mceFullScreen')
      }

      if (tinymce) {
        tinymce.destroy()
      }
    },
    setContent(value) {
      setTimeout(() => {
        this.$nextTick(() => {
          window.tinymce.get(this.tinymceId).setContent(value)
        })
      }, 1000)
    },
    getContent() {
      window.tinymce.get(this.tinymceId).getContent()
    },
    imageSuccessCBK(arr) {
      arr.forEach((v) => window.tinymce.get(this.tinymceId).insertContent(`<img class="wscnph" src="${v.url}" >`))
    },
    addEditorKeyWord(realStr) {
      // 获取富文本编辑器
      const ed = window.tinymce.get(this.tinymceId)
      var range = ed.selection.getRng()

      // 创建要插入的内容
      var divNode = ed.getDoc().createElement('span')
      divNode.innerHTML = realStr

      range.insertNode(divNode)
    }

  }
}
</script>

<style lang="scss" scoped>
.tinymce-container {
  position: relative;
  line-height: normal;
}

.tinymce-container {
  ::v-deep {
    .mce-fullscreen {
      z-index: 10000;
    }
  }
}

.tinymce-textarea {
  //visibility: hidden;
  z-index: -1;
}

.editor-custom-btn-container {
  position: absolute;
  right: 15px;
  top: 15px;
  z-index: 20;
}

.fullscreen .editor-custom-btn-container {
  z-index: 10000;
  position: fixed;
}

.editor-upload-btn {
  display: inline-block;
}

//隐藏右上角Upgrade
::v-deep .tox-promotion {
  display: none;
}
/deep/.tox-tinymce{
  min-height: 200px!important;
}
// 隐藏地步bar
/deep/.tox-statusbar{
  //display: none !important;
}
</style>
